package cn.slipi.message.biz;

import cn.slipi.common.exception.BizException;
import cn.slipi.common.utils.dozer.impl.ConvertBean;
import cn.slipi.facade.api.message.form.MessageForm;
import cn.slipi.message.handler.MessageHandler;
import cn.slipi.service.entity.TMessage;
import cn.slipi.service.service.TMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 独立消息服务biz
 */
@Component
public class MessageBiz {

    private static final Logger logger = LoggerFactory.getLogger(MessageBiz.class);

    @Autowired
    private ConvertBean convertBean;

    @Autowired
    private MessageHandler messageHandler;

    @Autowired
    private TMessageService messageService;

    public void prepareMessage(MessageForm messageForm) {
        logger.info("================预发消息：{}================", messageForm.getObjId());
        TMessage message = this.convertBean.convert(messageForm, TMessage.class);
        message.setState(0);
        this.messageService.getBaseMapper().insert(message);
    }

    @Transactional(rollbackFor = BizException.class)
    public void confirmMessage(String objId) {
        logger.info("================发送消息：{}================", objId);
        TMessage message = this.changeState(objId, 1);
        this.messageHandler.send(message.getRoutingKey(), message.getMessageContent());
    }

    public void completeMessage(String objId) {
        logger.info("================完成消息：{}================", objId);
        this.changeState(objId, 2);
    }

    /**
     * 修改消息状态
     *
     * @param objId
     * @param state
     * @return
     */
    private TMessage changeState(String objId, Integer state) {
        TMessage message = this.messageService.getMessageByObjId(objId);
        message.setState(state);
        this.messageService.getBaseMapper().updateById(message);
        return message;
    }
}
